package com.aicheyoudao;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.utils.DistanceUtil;

public class SearchResListAdapter extends BaseAdapter {

	private LayoutInflater inflater;
	private ArrayList<PoiInfo> listData;
	private LatLng mLatLng;
	private OnClickListener clicklis;

	public SearchResListAdapter(Context context, ArrayList<PoiInfo> listData, LatLng currentLocation, OnClickListener clicklis) {
		this.listData = listData;
		inflater = LayoutInflater.from(context);
		this.mLatLng = currentLocation;
		this.clicklis = clicklis;
	}

	@Override
	public int getCount() {
		return listData.size();
	}

	@Override
	public Object getItem(int position) {
		return listData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		viewHolder holder = null;
		if (convertView == null) {
			holder = new viewHolder();
			convertView = inflater.inflate(R.layout.near_search_res_item, parent, false);
			holder.name = (TextView) convertView.findViewById(R.id.search_res_name);
			holder.address = (TextView) convertView.findViewById(R.id.search_res_address);
			holder.distance = (TextView) convertView.findViewById(R.id.search_res_distance);
			holder.details = (TextView) convertView.findViewById(R.id.search_res_shopdetails);
			holder.cell = (TextView) convertView.findViewById(R.id.search_res_cell);
			holder.goNaviga = (TextView) convertView.findViewById(R.id.search_res_navigation);
			convertView.setTag(holder);
		} else {
			holder = (viewHolder) convertView.getTag();
		}
		holder.details.setTag(position);
		holder.cell.setTag(position);
		holder.goNaviga.setTag(position);

		holder.details.setOnClickListener(this.clicklis);
		holder.cell.setOnClickListener(this.clicklis);
		holder.goNaviga.setOnClickListener(this.clicklis);

		PoiInfo info = listData.get(position);
		holder.name.setText(info.name);
		holder.address.setText(info.address);
		double distance = DistanceUtil.getDistance(info.location, mLatLng);
		if (distance < 1000) {

			holder.distance.setText(String.valueOf(Math.round(distance)) + "m");
		} else {
			DecimalFormat df = new DecimalFormat("#.0");
			String disStr = String.valueOf(df.format(distance / 1000));
			holder.distance.setText(disStr + "Km");
		}

		return convertView;
	}

	class viewHolder {
		TextView name;
		TextView address;
		TextView distance;
		TextView details;
		TextView cell;
		TextView goNaviga;
	}

}
